import React, { ReactElement, InputHTMLAttributes, ChangeEvent } from "react";
import classNames from "classnames";
import { IconProp } from "@fortawesome/fontawesome-svg-core";
import Icon from "../Icon/icon";

type InputSize = "lg" | "sm";
// type

export interface BaseInputProps
  extends Omit<InputHTMLAttributes<HTMLElement>, "size"> {
  disabled?: boolean;
  size?: InputSize;
  icon?: IconProp;
  prepand?: string | ReactElement; //input前缀
  append?: string | ReactElement; //input后缀
  className?: string;
  style?: React.CSSProperties;
  onChange?: (e: ChangeEvent<HTMLInputElement>) => void;
}

const Input: React.FC<BaseInputProps> = (props) => {
  const {
    disabled,
    size,
    icon,
    prepand,
    append,
    className,
    style,
    ...restProps
  } = props;

  const classes = classNames("zs-input-wrapper", classNames, {
    [`input-size-${size}`]: size,
    "is-disabled": disabled,
    "input-group": prepand || append,
    "input-group-append": !!append,
    "input-group-prepend": !!prepand,
  });
  const fixControlledValue = (value: any) => {
    if (typeof value == "undefined" || value === null) {
      return "";
    } else {
      return value;
    }
  };
  if ("value" in props) {
    delete restProps.defaultValue;
    restProps.value = fixControlledValue(props.value);
  }

  return (
    <div className={classes} style={style}>
      {prepand ? <div className="zs-input-group-prepend">{prepand}</div> : ""}
      {icon && (
        <div className="icon-wrapper">
          <Icon icon={icon} theme="dark" title={`title-${icon}`} />
        </div>
      )}
      <input disabled={disabled} className="zs-input-inner" {...restProps} />
      {append ? <div className="zs-input-group-append">{append}</div> : ""}
    </div>
  );
};

export default Input;
